import React, { useState } from "react";
import { withRouter, Link } from "react-router-dom";
import style from "./style.module.scss";

function search(ev, history) {
  if (ev.keyCode === 13) {
    if (!ev.target.value) return;
    history.push(`/search/${ev.target.value}`);
  }
}

function handleChange(ev, setVal) {
  setVal(ev.target.value);
}

function Header(props) {
  const [val, setVal] = useState("");
  const { location } = props;
  if (["/404", "/login", "/register"].includes(location.pathname)) {
    return <div style={{ display: "none" }} />;
  }
  return (
    <nav className={style.header}>
      <Link to="/">
        <div className={style.logo}>CLITV</div>
      </Link>
      <div className={style.search}>
        <input
          value={val}
          type="search"
          placeholder="搜索一下又不会(⁄•⁄ω⁄•⁄)"
          onKeyDown={ev => search(ev, props.history)}
          onChange={ev => handleChange(ev, setVal)}
        />
      </div>
      <ul className={style.bar}>
        <li>
          <Link to="/">首页</Link>
        </li>
        <li>
          <Link to="/explore">发现</Link>
        </li>
        <li>
          <Link to="/login">登录</Link>
        </li>
        <li>
          <Link to="/register">注册</Link>
        </li>
      </ul>
    </nav>
  );
}

export default withRouter(Header);
